from typing import List, Optional
from sqlalchemy.orm import Session
from models.AccountUsage import AccountUsage
from schemas.AccountUsage import AccountUsageCreate, AccountUsageUpdate

class AccountUsageServe:
    @staticmethod
    def create(db: Session, accountusage: AccountUsageCreate) -> AccountUsage:
        db_obj = AccountUsage(**accountusage.dict())
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def get_by_id(db: Session, id: int) -> Optional[AccountUsage]:
        return db.query(AccountUsage).filter(AccountUsage.id == id, AccountUsage.isDelete != 1).first()

    @staticmethod
    def get_by_username(db: Session, username: str) -> Optional['AccountUsage']:
        return db.query(AccountUsage).filter(AccountUsage.username == username, AccountUsage.isDelete != 1).first()

    @staticmethod
    def get_all(db: Session, skip: int = 0, limit: int = 100) -> List[AccountUsage]:
        return db.query(AccountUsage).filter(AccountUsage.isDelete != 1).offset(skip).limit(limit).all()

    @staticmethod
    def update(db: Session, id: int, accountusage_update: AccountUsageUpdate) -> Optional[AccountUsage]:
        db_obj = db.query(AccountUsage).filter(AccountUsage.id == id, AccountUsage.isDelete != 1).first()
        if not db_obj:
            return None
        update_data = accountusage_update.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_obj, key, value)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    @staticmethod
    def delete(db: Session, id: int) -> bool:
        db_obj = db.query(AccountUsage).filter(AccountUsage.id == id, AccountUsage.isDelete != 1).first()
        if not db_obj:
            return False
        db_obj.isDelete = 1
        db.commit()
        return True